package com.zoffy.oj_backend.utils;

import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.InputStream;

@Component
@Slf4j
public class OSSUtils {
    @Value("${minio.endpoint}")
    private String endpoint;
    @Value("${minio.accessKey}")
    private String accessKey;
    @Value("${minio.secretKey}")
    private String secretKey;
    @Value("${minio.bucket}")
    private String bucket;
    private volatile MinioClient client;

    private MinioClient getInstance(){
        if(client==null){
            synchronized (OSSUtils.class){
                if(client==null){
                    client=MinioClient.builder().endpoint(endpoint).credentials(accessKey,secretKey).build();
                }
            }
        }
        return client;

    }
    public boolean upload(InputStream inputStream,String fileName){
        try{
            getInstance().putObject(PutObjectArgs.builder()
                    .bucket(bucket)
                    .object(fileName)
                    .stream(inputStream, -1, 10485760).build());
        }catch (Exception e){
            log.error("Minio文件上传失败:"+e.toString());
            return false;
        }
        return true;
    }
    public InputStream getObject(String filename){
        InputStream res;
        try {
            res = getInstance().getObject(GetObjectArgs.builder().bucket(bucket).object(filename).build());
        } catch (Exception e) {
            log.error("minio获取对象失败: "+e.toString());
            throw new RuntimeException(e);
        }
        return res;
    }
    //补全资源完整的url
    public String complementURL(String origin){
        return endpoint+bucket+"/"+origin;
    }
}
